package com.realgodo.site.service.space;

import java.util.Date;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springside.modules.orm.hibernate.DefaultEntityManager;

import com.realgodo.site.entity.space.Space;
import com.realgodo.site.entity.space.SpaceVisit;

@Service("spaceVisitManager")
@Transactional
public class SpaceVisitManager extends DefaultEntityManager<SpaceVisit, Long> {

	@Autowired
	protected SessionFactory sessionFactory;
	@Autowired
	private SpaceManager spaceManager;

	/**
	 * 创建或者 更新访问记录
	 * 
	 * @param spaceId
	 *            被访问
	 * @param visitId
	 *            访问者
	 * @return
	 */
	public SpaceVisit createSpaceVisit(Long spaceId, Long visitId) {
		SpaceVisit spaceVisit = null;
		if (spaceId != null && visitId != null) {
			spaceVisit = hasSpaceVisit(spaceId, visitId);
			if (spaceVisit != null) {

			} else {
				Space visit = spaceManager.get(visitId);
				spaceVisit = new SpaceVisit();
				spaceVisit.setSpaceId(spaceId);
				spaceVisit.setSpaceName(visit.getUser().getLoginName());
				spaceVisit.setVisitId(visitId);
				spaceVisit.setHeadPic(visit.getUser().getAvatar());
			}
			spaceVisit.setVisitDate(new Date());
			spaceVisit = (SpaceVisit) this.saveMerge(spaceVisit);
		}
		return spaceVisit;
	}

	/**
	 * 获取我的访问者
	 * 
	 * @param spaceId
	 *            被访问者
	 * @param max
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<SpaceVisit> getMySpaceVisitors(Long spaceId, int max) {
		Session session = this.sessionFactory.getCurrentSession();
		String hql = "select o from SpaceVisit o where o.spaceId = ? order by o.visitDate desc ";
		Query q = session.createQuery(hql);
		q.setParameter(0, spaceId);
		q.setMaxResults(max);
		return q.list();
	}

	/**
	 * 判断是否访问过
	 * 
	 * @param spaceId
	 * @param visitId
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public SpaceVisit hasSpaceVisit(Long spaceId, Long visitId) {
		Session session = this.sessionFactory.getCurrentSession();
		String hql = "select o  from SpaceVisit o where o.spaceId = ? and o.visitId = ?";
		Query q = session.createQuery(hql);
		q.setParameter(0, spaceId);
		q.setParameter(1, visitId);
		List<SpaceVisit> list = q.list();
		return (list != null && !list.isEmpty()) ? list.get(0) : null;
	}
}
